﻿using PLCS.Domain.Configs;
using PLCS.Shared.Common.Constant;

using Volo.Abp.DependencyInjection;

namespace PLCS.Domain;

/// <summary>
/// 配置类，默认启动会加载一遍，然后缓存到内存里
/// </summary>
public class PLCSConfigurationService
{
    private readonly IRepository<Config, Guid> _repository;
    private readonly object _lock = new object();
    private List<Config> _configs = new List<Config>();

    public PLCSConfigurationService(IRepository<Config, Guid> repository)
    {
        _repository = repository;
    }

    public async Task InitalAsync()
    {
        _configs = await LoadConfigurationFromDatabase();
    }

    /// <summary>
    /// 获取所有配置
    /// </summary>
    /// <returns></returns>
    public async Task<List<Config>> GetConfigurations()
    {
        if (!_configs.Any())
            await InitalAsync();
        return _configs;
    }

    /// <summary>
    /// 根据名称获取配置
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public async Task<string?> GetConfiguration(string name)
    {
        if (!_configs.Any())
            await InitalAsync();
        var config = _configs.SingleOrDefault(x => x.Name == name);
        if (config == null)
            return null;
        return config.Value;
    }

    /// <summary>
    /// 修改内存中的配置
    /// </summary>
    /// <param name="config"></param>
    public void UpdateConfiguration(Config config)
    {
        lock (_lock)
        {
            var configDto = _configs.SingleOrDefault(c => c.Name == config.Name);
            if (configDto == null)
                _configs.Add(config);
            else
            {
                _configs.Remove(configDto);
                _configs.Add(config);
            }
        }
    }

    public void DeleteConfiguration(Config config)
    {
        lock (_lock)
        {
            var configDto = _configs.SingleOrDefault(c => c.Name == config.Name);
            if (configDto != null)
                _configs.Remove(configDto);
        }
    }

    private async Task<List<Config>> LoadConfigurationFromDatabase()
    {
        var configs = await _repository.GetListAsync();
        return configs;
    }
}